// 在插件安装或更新时设置侧边栏
chrome.runtime.onInstalled.addListener(() => {
    // 设置侧边栏
    chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch((error) => {
        console.error('Failed to set panel behavior:', error);
    });
});

// 监听插件图标点击事件
chrome.action.onClicked.addListener((tab) => {
    // 切换侧边栏
    chrome.sidePanel.toggle();
});

// 监听下载请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'download') {
        downloadResource(request.url, request.filename);
        sendResponse({ status: 'started' });
    } else if (request.action === 'downloadAll') {
        downloadMultipleResources(request.resources);
        sendResponse({ status: 'started' });
    }
    return true;
});

// 下载单个资源
function downloadResource(url, filename) {
    chrome.downloads.download({
        url: url,
        filename: filename,
        saveAs: false
    });
}

// 下载多个资源
function downloadMultipleResources(resources) {
    resources.forEach((resource, index) => {
        // 添加延迟以避免触发下载限制
        setTimeout(() => {
            downloadResource(resource.src, resource.filename);
        }, index * 500);
    });
} 